package com.zzyk.microCloud.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.model.pojo.CommonCount;
import com.zzyk.main.model.pojo.MaintenanceInfo;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.vo.DateAndString;
import com.zzyk.main.model.vo.MaintenanceView;
import com.zzyk.main.model.vo.Message;
import com.zzyk.main.service.DeviceService;
import com.zzyk.main.service.MaintenanceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author wss_PC
 * @DESCRIPTION 维保控制器
 * @create 2020-6-23
 */
@RestController
@CrossOrigin(allowCredentials = "true")
@RequestMapping("/maintenance")
public class MaintenanceController extends BaseController {
    @Autowired
    private MaintenanceInfoService maintenanceInfoService;
    @Autowired
    private DeviceService deviceService;

    @GetMapping("/getInfoListExcel")
    public void getInfoListExcel(String dateTime,String token, HttpServletResponse response) throws UserException, IOException {
        SysUser sysUser = currentUserByToken(token);
        List<MaintenanceInfo> infoList = maintenanceInfoService.findInfoList(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
        ExcelWriter writer = ExcelUtil.getWriter();
        ArrayList<Map<String, Object>> rows = new ArrayList();
        for (MaintenanceInfo maintenanceInfo : infoList) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("设备名称", maintenanceInfo.getName());
            map.put("编号", maintenanceInfo.getSn());
            map.put("使用率", maintenanceInfo.getUsageRate());
            String tem = "";
            switch (maintenanceInfo.getSpecies()) {
                case 1:
                    tem = "定保";
                    break;
                case 2:
                    tem = "一级保养";
                    break;
                case 3:
                    tem = "二级保养";
                    break;
                case 4:
                    tem = "预防性维修";
                    break;
                case 5:
                    tem = "故障维修";
                    break;
            }
            map.put("维保种类", tem);
            map.put("计划时间", DateUtil.formatDate(DateUtil.offsetDay(maintenanceInfo.getLastMaintenanceTime(), maintenanceInfo.getMaintenanceCycle())));
            map.put("完成时间", maintenanceInfo.getMaintenanceTime());
            map.put("实施用时", maintenanceInfo.getTimeCost());
            map.put("维保内容", maintenanceInfo.getContent());
            map.put("更换材料清单", maintenanceInfo.getMaterialList());
            map.put("实施人", maintenanceInfo.getImplementer());
            map.put("检查验证人", maintenanceInfo.getCheckVerifier());
            rows.add(map);
        }
        writer.merge(10, "设备保养清单");
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("设备保养信息" + DateUtil.now() + ".xls").getBytes("GBK"), "ISO8859_1"));
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
// 关闭writer，释放内存
        writer.close();
//此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    @GetMapping("/getInfoList")
    public Message getInfoList(String dateTime) throws UserException {
        SysUser sysUser = currentUser();
        setPage();
        PageInfo<MaintenanceInfo> info = new PageInfo<>(maintenanceInfoService.findInfoList(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList()));
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    /**
     * 设备故障维修排行
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/getFailureRanking")
    public List<MaintenanceView> getFailureRanking(String dateTime) throws UserException {
        SysUser sysUser = currentUser();
        return maintenanceInfoService.findFailureRanking(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取结论里部分数据
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/getConclusion")
    public Message getConclusion(String dateTime) throws UserException {
        SysUser sysUser = currentUser();
        return maintenanceInfoService.findConclusion(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 查询日期范围内所有的维保数据 默认30天
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/getDateRangeMaintenance")
    public List<MaintenanceInfo> getDateRangeMaintenance(String dateTime) throws UserException {
        SysUser sysUser = currentUser();
        Integer[] deviceList = sysUser.getDeviceList();
        return maintenanceInfoService.findDateRangeMaintenance(dateTime, sysUser.getEnterprise(), deviceList);
    }

    /**
     * 根据设备ID查询维保情况维保倒计时，上次维保时间
     *
     * @param id
     * @return
     */
    @GetMapping("/getMaintenanceInfoByDId")
    public DateAndString getMaintenanceInfoByDId(Integer id) {
        return maintenanceInfoService.selectMaintenanceInfoByDId(id);
    }

    /**
     * 获取本月设备维保状态
     *
     * @return
     */
    @GetMapping("/getMaintenanceStatusThisMonth")
    public List<CommonCount> getMaintenanceStatusThisMonth() {
        /*  return maintenanceInfoService.findMaintenanceStatusThisMonth();*/
        return null;
    }

    /**
     * 添加或者修改采集设备维保信息
     *
     * @param maintenanceInfo
     * @return
     */
    @PostMapping("/saveOrUpdateCollectionMaintenance")
    public Message saveOrUpdateCollectionMaintenance(MaintenanceInfo maintenanceInfo) {
        try {
            if (maintenanceInfo.getMethodType() == 1) {
                maintenanceInfoService.updateByPrimaryKeySelective(maintenanceInfo);
                return Message.success();
            }
            maintenanceInfo.setType(0);
            maintenanceInfoService.insertSelective(maintenanceInfo);
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("保存失败");
        }
    }

    /**
     * 根据ID查询维保数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getMaintenanceBayId")
    public MaintenanceInfo getMaintenanceBayId(Integer id) {
        return maintenanceInfoService.selectByPrimaryKey(id);
    }

    /**
     * 删除维保数据
     *
     * @param id
     * @return
     */
    @GetMapping("/deleteMaintenance")
    public Message deleteMaintenance(Integer id) {
        try {
            maintenanceInfoService.deleteMaintenanceByPrimaryKey(id);
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("删除失败");
        }
    }

    @GetMapping("/countMaintenanceInfoByParam")
    public Message countMaintenanceInfoByParam(String dateTime, Integer type, String name, Integer deviceType) throws UserException {
        String beginTime = "";
        String endTime = "";
        if (StringUtils.isNotBlank(dateTime)) {
            String[] split = dateTime.split(" ~ ");
            beginTime = split[0];
            endTime = split[1];
        }
        SysUser user = currentUser();
        return Message.success()
                .addData("data", maintenanceInfoService.countMaintenanceInfoByParam(beginTime, endTime, type, user.getEnterprise(), null, name, deviceType, user.getDeviceList()));

    }

    /**
     * 根据维保时间查询记录 参数为空查询全部
     *
     * @param dateTime
     * @param type     区分生产和采集
     * @return
     */
    @GetMapping("/getMaintenanceInfoByParam")
    public Message getMaintenanceInfoByParam(String dateTime, Integer type, String name, Integer deviceType) throws UserException {
        String beginTime = "";
        String endTime = "";
        if (StringUtils.isNotBlank(dateTime)) {
            String[] split = dateTime.split(" ~ ");
            beginTime = split[0];
            endTime = split[1];
        }
        SysUser user = currentUser();
        setPage();
        PageInfo<MaintenanceInfo> info = new PageInfo<>(maintenanceInfoService.selectAllByParam(beginTime, endTime, type, user.getEnterprise(), null, name, deviceType, user.getDeviceList()));
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    /**
     * 添加生产设备维保信息并进行文件上传，APP
     *
     * @param sn
     * @param content
     * @param maintenanceTime
     * @param methodType
     * @param photoFile
     * @return
     */
    @PostMapping("/saveOrUpdateMaintenanceApp")
    public Message saveOrUpdateMaintenanceApp(String sn, String content, Date maintenanceTime, Integer methodType, MultipartFile photoFile) throws IOException, UserException {
        MaintenanceInfo maintenanceInfo = new MaintenanceInfo();
        maintenanceInfo.setSn(sn);
        maintenanceInfo.setContent(content);
        maintenanceInfo.setMaintenanceTime(maintenanceTime);
        maintenanceInfo.setMethodType(methodType);
        maintenanceInfo.setPhotoFile(photoFile);

        if (maintenanceInfo.getMethodType() == 1) {
            maintenanceInfo.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
            maintenanceInfoService.updateByPrimaryKeyAndFileUpload(maintenanceInfo, null);
            return Message.success();
        }
        maintenanceInfoService.insertMaintenanceInfo(maintenanceInfo, null);
        return Message.success();

    }

    /**
     * 添加生产设备维保信息并进行文件上传，应该可以共用。
     *
     * @param maintenanceInfo
     * @return
     */
    @PostMapping("/saveOrUpdateMaintenance")
    public Message saveOrUpdateMaintenance(MaintenanceInfo maintenanceInfo) throws IOException, UserException {

        if (maintenanceInfo.getMethodType() == 1) {
            maintenanceInfo.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
            maintenanceInfoService.updateByPrimaryKeyAndFileUpload(maintenanceInfo, null);
            return Message.success();
        }
        maintenanceInfoService.insertMaintenanceInfo(maintenanceInfo, null);
        return Message.success();

    }

    @RequestMapping("list")
    public Message getMaintenanceByCompany() throws UserException {
        SysUser user = currentUser();
        return Message.success().
                addData("data", deviceService.getMaintenanceList(null, user.getEnterprise(), user.getDeviceList()))
                .addData("extension", deviceService.getExtensionMaintenanceInfo(null, user.getEnterprise(), user.getDeviceList()));

    }
}